import axios from 'axios';

// Ensure we're getting the correct API URL
const API_BASE_URL = process.env.REACT_APP_API_BASE_URL || 'http://localhost:8000';
console.log('Using API base URL:', API_BASE_URL);

const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
  // Increase timeout to 30 seconds
  timeout: 30000,
  withCredentials: false,
});

// Add request interceptor for debugging
api.interceptors.request.use(
  (config) => {
    console.log(`Making ${config.method.toUpperCase()} request to: ${config.baseURL}${config.url}`);
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Add response interceptor for debugging
api.interceptors.response.use(
  (response) => {
    console.log(`Received response from: ${response.config.url}`);
    return response;
  },
  (error) => {
    console.error('API Error:', error.message, error.config?.url);
    return Promise.reject(error);
  }
);

// 重试逻辑
const retryRequest = async (fn, retries = 3, delay = 1000) => {
  try {
    return await fn();
  } catch (error) {
    if (retries <= 0) throw error;

    console.log(`Retrying request... (${retries} attempts left)`);
    await new Promise(resolve => setTimeout(resolve, delay));
    return retryRequest(fn, retries - 1, delay * 1.5);
  }
};

export const chatService = {
  // 发送消息到后端
  sendMessage: async (message) => {
    try {
      const response = await retryRequest(() => api.post('/chat', message));
      return response.data;
    } catch (error) {
      console.error('Error sending message:', error);
      throw error;
    }
  },

  // 获取会话列表
  getConversations: async () => {
    try {
      const response = await retryRequest(() => api.get('/conversations'));
      return response.data;
    } catch (error) {
      console.error('Error fetching conversations:', error);
      // Return empty array instead of failing completely
      return [];
    }
  },

  // 获取特定会话的消息
  getMessages: async (conversationId) => {
    try {
      const response = await retryRequest(() => api.get(`/conversations/${conversationId}/messages`));
      return response.data;
    } catch (error) {
      console.error(`Error fetching messages for conversation ${conversationId}:`, error);
      // Return empty array instead of failing completely
      return [];
    }
  },

  // 创建新会话
  createConversation: async (title = '新对话') => {
    try {
      const response = await retryRequest(() => api.post('/conversations', { title }));
      return response.data;
    } catch (error) {
      console.error('Error creating conversation:', error);
      throw error;
    }
  },

  // 上传文件
  uploadFile: async (file) => {
    const formData = new FormData();
    formData.append('file', file);

    try {
      const response = await retryRequest(() =>
        api.post('/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        })
      );
      return response.data;
    } catch (error) {
      console.error('Error uploading file:', error);
      throw error;
    }
  },
};

export const connectToStream = (data, onMessage, onDone, onError) => {
  console.log('Connecting to stream with data:', data);

  // 构建查询参数
  const queryParams = new URLSearchParams({
    data: JSON.stringify(data)
  }).toString();

  // 创建EventSource对象
  const eventSource = new EventSource(`${API_BASE_URL}/stream?${queryParams}`);

  // 设置连接超时
  const timeoutId = setTimeout(() => {
    console.error('Stream connection timeout after 30 seconds');
    eventSource.close();
    onError(new Error('连接超时，请检查后端服务'));

    // 使用模拟消息作为后备方案
    onMessage({ text: `很抱歉，连接超时。您的问题是: "${data.message}"` });
    setTimeout(() => onDone(), 500);
  }, 30000);

  // 连接打开事件
  eventSource.onopen = () => {
    console.log('Stream connection opened');
  };

  // 收到消息事件
  eventSource.onmessage = (event) => {
    try {
      console.log('Stream message received:', event.data);

      // 清除超时
      clearTimeout(timeoutId);

      // 解析消息内容
      const data = JSON.parse(event.data);

      // 回调处理消息
      if (data && data.text) {
        onMessage(data);
      } else {
        console.warn('Received message with no text:', data);
      }
    } catch (error) {
      console.error('Error parsing SSE message:', error, event.data);
    }
  };

  // 完成事件
  eventSource.addEventListener('done', (event) => {
    console.log('Stream completed');
    clearTimeout(timeoutId);
    eventSource.close();
    onDone();
  });

  // 错误事件
  eventSource.onerror = (error) => {
    console.error('SSE Error:', error);
    clearTimeout(timeoutId);
    eventSource.close();

    // 回调处理错误
    onError(error);

    // 提供后备消息，但仅当没有收到任何消息时
    onMessage({ text: "连接出错，请稍后再试。" });
    setTimeout(() => onDone(), 500);
  };

  // 返回清理函数
  return () => {
    console.log('Closing stream connection');
    clearTimeout(timeoutId);
    eventSource.close();
  };
};